using System;
using Godot;

public partial class PickUnit : Node3D
{
	public Node3D result = null;
	public Action<Node3D> onPick = null;

	public override void _Ready()
	{
		SetProcessInput(true);
	}

	public override void _Process(double delta)
	{
		if (Input.IsActionJustPressed("PickUnit"))
		{
			if(result != null)
			{
				(result as IPickable)?.OnUnPick();
			}
			result = CaptureObjectUnderMouse();
			if (result != null)
			{
				onPick?.Invoke(result);
				if (result is IPickable onPickInterface)
				{
					onPickInterface.OnPick();
				}
				return;
			}

		}
	}

	private Node3D CaptureObjectUnderMouse()
	{
		// 获取鼠标位置
		Vector2 mousePosition = GetViewport().GetMousePosition();
		// 创建射线查询参数
		var from = GetViewport().GetCamera3D().ProjectRayOrigin(mousePosition);
		var to = from + GetViewport().GetCamera3D().ProjectRayNormal(mousePosition) * 1000; // 射线长度可以根据需要调整


		// 执行射线查询
		var spaceState = GetWorld3D().DirectSpaceState;
		var query = PhysicsRayQueryParameters3D.Create(from, to);
		var result = spaceState.IntersectRay(query);

		if (result.Count > 0)
		{
			var colider = result["collider"].As<Node3D>();
			if (colider != null)
			{
				return colider;
			}
		}
		return null;
	}
}
